package com.gitee.huanminabc.dynamicdb.interceptor;

import com.gitee.huanminabc.dynamicdb.common.Constants;
import com.gitee.huanminabc.dynamicdb.core.DBContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: java-huanmin-utils
 * @description: 多租户拦截器
 * @author: huanmin
 * @create: 2024-12-09 14:55
 **/
@Slf4j
public class DBTenantInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置默认的数据源
        DBContext.dbKeys.set(Constants.DEFAULT_DB_KEY);

        //获取请求头中的租户标识
        String tenant = request.getHeader(Constants.TENANT_KEY);
        if (tenant == null) {
            return true;
        }
        //如果不是空那么设置租户标识
        DBContext.tenantKeys.set(tenant);
        String requestURI = request.getRequestURI();
        log.info("{}租户标识{}",requestURI, tenant);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空多数据源的标识
        DBContext.clear();
    }
}
